package config

import (
	"github.com/shima-park/agollo"
	"github.com/spf13/cast"
	"github.com/spf13/viper"
	"os"
	"strings"
	"time"
)

//初始化apollo
func InitApolloConfig() (apolloConfig agollo.Agollo) {
	//获取配置
	apolloAppID := getApolloAppId()
	apolloCluster := getApolloCluster()
	apolloServerUrl := getApolloServerUrl()
	apolloNamespaceName := getApolloNamespace()
	apolloBackupConfigPath := getApolloBackupConfigPath()
	apolloLongPoller := getApolloLongPoller()
	apolloAaccessKey := getApolloAccessKey()

	// 未配置apollo,返回
	if len(apolloAppID) == 0 {
		return
	}
	// new apollo
	apolloConfig, err := agollo.New(
		apolloServerUrl,
		apolloAppID,
		agollo.Cluster(apolloCluster),
		agollo.DefaultNamespace(apolloNamespaceName[0]),                        //第一个为默认命名空间
		agollo.PreloadNamespaces(apolloNamespaceName...),                       //预设多命名空间
		agollo.FailTolerantOnBackupExists(),                                    //服务器连接失败时允许读取备份
		agollo.BackupFile(apolloBackupConfigPath),                              //备份
		agollo.LongPollerInterval(time.Duration(apolloLongPoller)*time.Second), //轮询
		agollo.WithClientOptions(
			agollo.WithAccessKey(apolloAaccessKey),
		), //访问秘钥
	)
	if err != nil {
		panic(err.Error())
	}

	//启动go监听变化，并更新agollo对象内的配置cache
	apolloConfig.Start()
	return
}

func getApolloAppId() string {
	//优先配置文件
	appId := viper.GetString("apollo.AppID")
	if appId != "" {
		return appId
	}

	//其次环境变量
	return os.Getenv("APP_ID")
}

func getApolloCluster() string {
	//优先配置文件
	cluster := viper.GetString("apollo.Cluster")
	if cluster != "" {
		return cluster
	}

	//其次环境变量
	return os.Getenv("IDC")
}

func getApolloServerUrl() string {
	//优先配置文件
	servelUrl := viper.GetString("apollo.ServerUrl")
	if servelUrl != "" {
		return servelUrl
	}

	//其次环境变量
	return os.Getenv("APOLLO_META")
}

func getApolloNamespace() []string {
	//优先配置文件
	namespace := viper.GetStringSlice("apollo.NamespaceName")
	if len(namespace) != 0 {
		return namespace
	}

	//其次环境变量
	ns := os.Getenv("APOLLO_NAMESPACES")
	return strings.Split(ns, ",")
}

func getApolloBackupConfigPath() string {
	//优先配置文件
	confPath := viper.GetString("apollo.BackupConfigPath")
	if confPath != "" {
		return confPath
	}

	//其次环境变量
	return os.Getenv("APOLLO_CACHE_FILE")
}

func getApolloLongPoller() int {
	//优先配置文件
	longPoller := viper.GetInt("apollo.LongPoller")
	if longPoller != 0 {
		return longPoller
	}

	//其次环境变量
	alp := cast.ToInt(os.Getenv("APOLLO_LONG_POLLER"))
	if alp != 0 {
		return alp
	}

	//最后默认值
	return 10
}

func getApolloAccessKey() string {
	//优先配置文件
	accessKey := viper.GetString("apollo.AccessKey")
	if accessKey != "" {
		return accessKey
	}

	//其次环境变量
	return os.Getenv("APOLLO_ACCESS_KEY_SECRET")
}
